package design.mode.iterator.item1;


import java.util.NoSuchElementException;

/**
 * /**
 *
 * @author ZhongMingde on 2021/11/20
 */

public class ArrayIterator<E> implements Iterator<E> {

  private int cursor;

  private ArrayList<E> arrayList;

  public ArrayIterator( ArrayList<E> arrayList) {
    this.cursor = 0;
    this.arrayList = arrayList;
  }

  @Override
  public boolean hasNext() {
    return cursor != arrayList.size(); //注意这里，cursor在指向最后一个元素的时候，hasNext()仍旧返回true。
  }

  @Override
  public void next() {
    cursor++;
  }

  @Override
  public E currentItem() {
    if (cursor >= arrayList.size()) {
      throw new NoSuchElementException();
    }
    return arrayList.get(cursor);
  }

  public static void main(String[] args) {
    ArrayList names = new ArrayList<>();
    names.add("xzg");
    names.add("wang");
    names.add("zheng");
    Iterator iterator = new ArrayIterator(names);
    while (iterator.hasNext()) {
      System.out.println(iterator.currentItem());
      iterator.next();
    }
  }
}
